package com.lqian.share;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 无锁化 自旋 compare and set/swap
 * cas (V,Expected,NewValue){
 *     if(V == Expected) V = NEW;
 *     otherwise try again or fail;
 * }
 * cpu原语支持(指令不能被打断)
 */
public class T_AtomicInteger_02 {
    /*volatile*/ //int count = 0;
    AtomicInteger count = new AtomicInteger(0);


    void m(){
        for (int i = 0; i <10000 ; i++){
            count.incrementAndGet(); //count++;
        }
    }

    public static void main(String[] args){
        T_AtomicInteger_02 t = new T_AtomicInteger_02();

        ArrayList<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 10 ; i++) {
            threads.add(new Thread(t::m,"thread-"+i));
        }

        threads.forEach(o->o.start());
        threads.forEach((o)->{
            try {
                o.join();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        System.out.println(t.count);
    }
}
